<template>
	<div id="comment">
		<header>
			<h4>提交评论</h4>
			<hr />
			<textarea placeholder="请输入您要评论的内容..." v-model.trim="text"></textarea>
			<mt-button @click="subComment" type="primary" size="large">发表</mt-button>
		</header>
		<main>
			<h4>评论列表</h4>
			<hr />
			<ul>
				<li v-for="(item,index) in list" :key='index'>
					<div class="title"><span>第{{index+1}}楼</span><span>用户：{{item.user_name}}</span><span>发表时间：{{item.add_time | datefmt('YYYY-MM-DD HH:mm:ss')}}</span></div>
					<p>{{item.content}}</p>
				</li>
			</ul>
			<mt-button @click="getMore" type="danger" size="large">查看更多</mt-button>
		</main>
	</div>
</template>

<script>
	import { Button } from 'mint-ui';
	import { Toast } from 'mint-ui';
	export default {
		props: ['id', 'artid'],
		data() {
			return {
				list: [],
				pageIndex: 1,
				text: '',
				length: 0,
				comId: 0
			}
		},
		created() {
			this.comId = this.id || this.artid;
			console.log(this.comId);
			console.log('新闻的' + this.id + '图片的' + this.artid);
			this.getCommentList(this.pageIndex);
		},
		methods: {
			getCommentList(pageIndex) {
				pageIndex = pageIndex || 1;
				this.$http.get(this.$common.domain + '/api/getcomments/' + this.comId + '?pageindex=' + pageIndex).then(function(res) {
					if(res.body.status != 0) {
						Toast(res.body.message);
						return;
					}
					if(res.body.message.length === 0 && pageIndex > 1) {
						Toast({
							message: '没有更多数据了',
							position: 'bottom',
							duration: 3000
						});
						this.pageIndex--;
						return;
					}
					this.list = this.list.concat(res.body.message);
				});
			},
			subComment() {
				if(!this.text) {
					Toast({
						message: '评论不能为空！'
					});
					return;
				}
				this.$http.post(this.$common.domain + '/api/postcomment/' + this.comId, {
					content: this.text
				}, {
					emulateJSON: true
				}).then(function(res) {
					if(res.body.status != 0) {
						Toast({
							message: '评论提交失败'
						});
					}
					Toast({
						message: res.body.message,
						iconClass: 'icon icon-success'
					});
					this.list.unshift({
						"user_name": "匿名用户",
						"add_time": new Date(),
						"content": this.text
					});
					this.text = '';
				});
			},
			getMore() {
				this.pageIndex++;
				this.getCommentList(this.pageIndex);
			}
		}
	}
</script>

<style scoped>
	header {
		margin-top: 50px;
	}
	
	h4 {
		font-size: 24px;
	}
	
	.title {
		font-size: 14px;
		background-color: gray;
		color: white;
		padding-left: 10px;
		line-height: 1.5em;
		border: 1px solid gray;
		border-radius: 4px;
	}
	
	.title span {
		margin-right: 15px;
	}
	
	main {
		margin: 40px 0;
	}
	
	li>p {
		text-indent: 2em;
		font-size: 20px;
		line-height: 1.5em;
	}
</style>